#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    connect(&threadB, SIGNAL(started()), this, SLOT(on_threadB_started()));
    connect(&threadB, SIGNAL(finished()), this, SLOT(on_threadB_finished()));
    connect(&threadB, SIGNAL(newValue(int,int)), this, SLOT(on_threadB_newValue(int,int)));
}

Dialog::~Dialog()
{
    delete ui;
}
void Dialog::on_threadB_newValue(int seq, int diceValue){
    QString str = QString::asprintf("第 %d 次掷骰子， 值为 %d", seq, diceValue);
    ui -> plainTextEdit ->setPlainText(str);
}

void Dialog::on_threadB_started(){
    ui -> consumer -> setText("consumer 状态  开启");
}

void Dialog::on_threadB_finished(){
    ui -> consumer -> setText("consumer 状态  关闭");
}

void Dialog::on_threadStart_clicked()
{
    threadB.start(); //顺序不应该调换，先consumer 后 producer
    threadA.start();
    ui->threadStart->setEnabled(false);
    ui->stopThread->setEnabled(true);
    ui -> producer -> setText("producer 状态  开启");
}

void Dialog::on_stopThread_clicked()
{
    threadA.stopThread();
    threadA.wait();
    threadB.terminate();
    threadB.wait();
    ui->threadStart->setEnabled(true);
    ui->stopThread->setEnabled(false);
    ui -> producer -> setText("producer 状态  关闭");
}

void Dialog::on_clearText_clicked()
{
    ui -> plainTextEdit->clear();
}

void Dialog::closeEvent(QCloseEvent *event){
    if (threadA.isRunning()){
        threadA.stopThread();
        threadA.wait();
    }
    event->accept();
}
